package com.cloudfun.msglisten.config;

import com.cloudfun.msglisten.util.RabbitConfigUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.amqp.RabbitProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by Huqin on 2020/4/1
 */
@Slf4j
@Configuration
public class ExternalRabbitConfig {

    @Autowired
    private MessageConverter messageConverter;

    @Bean
    public CachingConnectionFactory externalConnectionFactory(ExternalRabbitProperties properties) {
        RabbitProperties rabbitProperties = new RabbitProperties();
        BeanUtils.copyProperties(properties, rabbitProperties);
        return RabbitConfigUtils.cachingConnectionFactory(rabbitProperties, null);
    }

    @Bean
    public RabbitAdmin externalRabbitAdmin(@Qualifier("externalConnectionFactory") ConnectionFactory connectionFactory) {
        return new RabbitAdmin(connectionFactory);
    }

    @Bean
    public RabbitTemplate externalRabbitTemplate(@Qualifier("externalConnectionFactory") ConnectionFactory connectionFactory,
                                                 RabbitMsgCallback rabbitMsgCallback) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(messageConverter);
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setConfirmCallback(rabbitMsgCallback);
        rabbitTemplate.setReturnCallback(rabbitMsgCallback);
        return rabbitTemplate;
    }

}
